<template>
  <div class="app-container">
    <el-card shadow="never">
      <el-row :gutter="48">
        <!--部门数据-->
        <el-col :span="4" :xs="24">
          <div class="head-container">
            <el-input v-model="deptName" placeholder="部门名称" clearable size="small" prefix-icon="el-icon-search" style="margin-bottom: 20px" />
          </div>
          <div class="head-container">
            <el-tree ref="tree" :data="deptOptions" :props="defaultProps" :expand-on-click-node="false" :filter-node-method="filterNode" default-expand-all @node-click="handleNodeClick" />
          </div>
        </el-col>

        <el-col :span="20" :xs="24">
          <!-- 查询、筛选条件 -->

          <el-form v-show="showSearch" ref="queryForm" :model="queryParams" label-position="left" label-width="85px">
            <el-row :gutter="48">
              <el-col :xs="24" :sm="8">
                <el-form-item label="登录账号：" prop="userIds">
                  <select-user-by-dept v-model="queryParams.userIds" placeholder="请选择" size="small" multi />
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="8">
                <el-form-item label="手机号码：" prop="phonenumber">
                  <el-input v-model="queryParams.phonenumber" placeholder="请输入" clearable size="small" @keyup.enter.native="handleQuery" />
                </el-form-item>
              </el-col>
              <!-- 高级筛选 默认隐藏 -->
              <template v-if="advanced">
                <el-col :xs="24" :sm="8">
                  <el-form-item label="状态：" prop="status">
                    <el-select v-model="queryParams.status" placeholder="用户状态" clearable size="small" style="width: 100%">
                      <el-option v-for="dict in statusOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="8">
                  <el-form-item label="创建时间：">
                    <el-date-picker v-model="dateRange" size="small" style="width: 100%" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" />
                  </el-form-item>
                </el-col>
              </template>
              <el-col :xs="24" :sm="!advanced && 8 || 24">
                <span class="search-advancedButton">
                  <el-button v-waves type="primary" size="small" @click="handleQuery">查 询</el-button>
                  <el-button size="small" @click="resetQuery">重 置</el-button>
                  <el-button type="text" @click="advanced = !advanced">
                    {{ advanced ? '收起' : '展开' }}
                    <i :class="[!advanced && 'arrow-up' || 'arrow-down' ,'el-icon-arrow-up']" />
                  </el-button>
                </span>
              </el-col>
            </el-row>
          </el-form>

          <!-- 新增 -->
          <el-row :gutter="10" class="mb16">
            <el-col :span="1.5">
              <el-button v-hasPermi="['system:user:add']" type="primary" plain icon="el-icon-plus" size="small" @click="handleAdd">新增</el-button>
            </el-col>

            <!-- 删除 -->
            <transition name="el-fade-in-linear">
              <el-col v-if="ids.length > 0" :span="1.5">
                <el-button v-hasPermi="['system:user:remove']" type="danger" plain icon="el-icon-delete" size="small" :disabled="multiple" @click="handleDelete">删除</el-button>
              </el-col>
            </transition>

            <!-- 工具栏 -->
            <right-toolbar :show-search.sync="showSearch" :show-download.sync="showDownload" :columns="columns" @queryTable="getList">
              <template slot="download">
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item v-hasPermi="['system:user:import']" icon="el-icon-upload2" @click.native="upload.show = true">导入</el-dropdown-item>
                  <el-dropdown-item v-hasPermi="['system:user:export']" divided icon="el-icon-download" @click.native="handleExport">导出</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </right-toolbar>
          </el-row>

          <!-- 表格 -->
          <el-table ref="userTable" v-loading="loading" :data="userList" @row-click="handleCheck" @selection-change="handleSelectionChange">
            <template slot="empty">
              <el-empty />
            </template>
            <el-table-column type="selection" width="80" align="center" />
            <el-table-column v-if="columns[2].visible" key="nickName" label="用户名" align="left" prop="nickName" :show-overflow-tooltip="true">
              <template slot-scope="{row}">
                <div class="table_nickName">
                  <div style="margin:2px 8px 0 0">
                    <el-avatar v-if="row.avatar" :key="row.avatar" shape="circle" size="medium" :src="`${process}${row.avatar}`" />
                    <el-avatar v-else>
                      <img src="@/assets/images/profile.png">
                    </el-avatar>
                  </div>
                  {{ row.nickName }}
                </div>
              </template>
            </el-table-column>
            <el-table-column v-if="columns[1].visible" key="userName" label="登录账号" align="left" prop="userName" :show-overflow-tooltip="true" />
            <el-table-column v-if="columns[4].visible" key="phonenumber" label="手机号码" align="left" prop="phonenumber" />
            <el-table-column key="deptName" label="所属部门" align="center" prop="dept.deptName" />
            <el-table-column key="sex" width="50" label="性别" align="center">
              <template slot-scope="{row}">
                <svg-icon style="font-size:20px;" :icon-class="row.sex === '1'? 'nan': 'nv' " />
              </template>
            </el-table-column>
            <el-table-column v-if="columns[5].visible" key="status" label="状态" align="center">
              <template slot-scope="{row}">
                <el-dot :type="row.status === '0' ? 'success' :'error'" />
                <span class="badge-status-text">{{ statusFormat(row) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" fixed="right" align="center" width="160" class-name="small-padding fixed-width">
              <template slot-scope="{row}">
                <el-button v-hasPermi="['system:user:edit']" size="small" type="text" @click="handleEdit(row)">编辑</el-button>
                <el-divider direction="vertical" />
                <el-button v-hasPermi="['system:user:resetPwd']" size="small" type="text" @click="handleResetPwd(row)">重置</el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />
        </el-col>
      </el-row>

      <!-- 新增|编辑|查看 用户信息 -->
      <user-info ref="userInfo" :show.sync="userInfo.open" @close="getList" />

      <!-- 导入 -->
      <zrk-upload :show.sync="upload.show" title="用户导入" :import-url="upload.importUrl" :template-url="upload.templateUrl" width="750" :accept="upload.accept" @close="getList" />
    </el-card>
  </div>
</template>

<script>
import { listUser, delUser, exportUser, resetUserPwd } from '@/api/system/user'
import { userMixin } from '@/views/system/user/mixins/userMixin'
import SelectUserByDept from '@/components/Zrk/SelectUserByDept'
import userInfo from './modules/userInfoDrawer'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'

export default {
  name: 'User',
  components: { userInfo, SelectUserByDept },
  mixins: [userMixin],
  data() {
    return {
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 显示下载工具
      showDownload: true,
      // 高级查询
      advanced: false,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: null,
      // 弹出层标题
      title: '',
      // 部门树选项
      deptOptions: undefined,
      // 是否显示弹出层
      open: false,
      // 部门名称
      deptName: undefined,
      // 日期范围
      dateRange: [],
      // 表单参数
      userInfo: {
        open: false,
        form: {}
      },
      form: {},
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层
        show: false,
        // 导入路径
        importUrl: '/system/user/importData',
        // 模板路径
        templateUrl: '/system/user/importTemplate',
        // 类型限制
        accept: '.xls,.xlsx'
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        phonenumber: undefined,
        status: undefined,
        deptId: undefined
      },
      // 列信息
      columns: [
        { key: 0, label: `用户编号`, visible: true },
        { key: 1, label: `用户名称`, visible: true },
        { key: 2, label: `用户昵称`, visible: true },
        { key: 3, label: `部门`, visible: true },
        { key: 4, label: `手机号码`, visible: true },
        { key: 5, label: `状态`, visible: true },
        { key: 6, label: `创建时间`, visible: true }
      ]
    }
  },

  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val)
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询用户列表 */
    getList() {
      this.loading = true
      listUser(this.addDateRange(this.queryParams, this.dateRange)).then(
        (response) => {
          this.userList = response.rows
          this.total = response.total
          this.loading = false
        }
      )
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.deptId = data.id
      this.getList()
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.userId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.userInfo.open = true
      this.$refs.userInfo.add()
    },
    /** 修改按钮操作 */
    handleEdit(row) {
      this.userInfo.open = true
      this.$refs.userInfo.edit(row)
    },
    /** 查看按钮操作 */
    handleCheck(row, column) {
      /* eslint-disable */
      if (!!column.fixed) {
        return
      }
      this.userInfo.open = true
      this.$refs.userInfo.check(row)
    },
    /** 重置密码按钮操作 */
    handleResetPwd(row) {
      this.$prompt('请输入"' + row.nickName + '"的新密码', '重置密码', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      })
        .then(({ value }) => {
          resetUserPwd(row.userId, value).then((response) => {
            this.msgSuccess('修改成功，新密码是：' + value)
          })
        })
        .catch(() => {})
    },
    /** 删除按钮操作 */
    handleDelete() {
      const userIds = this.ids
      this.$confirm(
        '是否确认删除用户编号为"' + userIds + '"的数据项?',
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(function () {
          return delUser(userIds)
        })
        .then(() => {
          this.getList()
          this.msgSuccess('删除成功')
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams
      this.$confirm('是否确认导出所有用户数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(function () {
          return exportUser(queryParams)
        })
        .then((response) => {
          this.download(response.msg)
        })
    }
  }
}
</script>

<style lang="scss" scoped>
.table_nickName {
  margin: 1px 0 !important;
  display: flex;
  align-items: center;
}

::v-deep .el-table__expanded-cell {
  padding: 15px 115px !important;
}
</style>
